<?php
require_once 'Database.php';
require_once 'OrderManager.php';
require_once 'CDKManager.php';
require_once 'ProductManager.php';

/**
 * 易支付集成类
 */
class EasyPay {
    private $db;
    private $config;

    public function __construct() {
        $this->db = Database::getInstance();
        $this->config = $this->getConfig();
    }

    /**
     * 获取支付配置
     */
    private function getConfig() {
        // 从数据库获取配置，如果不存在则使用默认值
        $defaultConfig = [
            'api_url' => 'https://zf.tuour.com/submit.php',
            'pid' => '1000',
            'key' => '0NPL2l2lQ20Dq2pzDl88qP44qmcy2c2j',
            'notify_url' => 'http://localhost/cdkpay/notify.php',
            'return_url' => 'http://localhost/cdkpay/return.php'
        ];
        
        try {
            $settings = $this->db->query("SELECT setting_key, setting_value FROM system_settings WHERE setting_key LIKE 'easypay_%'");
            
            if (!empty($settings)) {
                foreach ($settings as $setting) {
                    $key = str_replace('easypay_', '', $setting['setting_key']);
                    if (array_key_exists($key, $defaultConfig)) {
                        $defaultConfig[$key] = $setting['setting_value'];
                    }
                }
            }
        } catch (Exception $e) {
            // 如果表不存在，使用默认配置
            error_log("获取支付配置失败: " . $e->getMessage());
        }
        
        return $defaultConfig;
    }

    /**
     * 创建支付请求
     */
    public function createPayment($orderNo, $amount, $paymentType = 'alipay', $productName = '') {
        $params = [
            'pid' => $this->config['pid'],
            'type' => $paymentType,
            'out_trade_no' => $orderNo,
            'notify_url' => $this->config['notify_url'],
            'return_url' => $this->config['return_url'],
            'name' => $productName ?: '商品购买',
            'money' => sprintf('%.2f', $amount),
            'sitename' => 'CDK支付系统'
        ];

        // 生成签名
        $params['sign'] = $this->generateSign($params);
        $params['sign_type'] = 'MD5';

        // 记录支付请求
        $this->logPaymentRequest($orderNo, $params);

        return [
            'payment_url' => $this->config['api_url'] . '?' . http_build_query($params),
            'params' => $params
        ];
    }

    /**
     * 生成签名
     */
    private function generateSign($params) {
        ksort($params);
        $signString = '';
        
        foreach ($params as $key => $value) {
            if ($key != 'sign' && $key != 'sign_type' && $key != 'subid1' && $value != '') {
                $signString .= $key . '=' . $value . '&';
            }
        }
        
        $signString = rtrim($signString, '&');
        $signString .= $this->config['key'];
        
        return md5($signString);
    }

    /**
     * 验证支付回调
     */
    public function verifyNotify($postData) {
        if (empty($postData)) {
            return false;
        }

        // 保存原始签名
        $sign = $postData['sign'] ?? '';
        $signType = $postData['sign_type'] ?? '';
        
        // 创建用于签名的参数副本
        $signParams = $postData;
        unset($signParams['sign']);
        unset($signParams['sign_type']);

        // 生成本地签名
        $localSign = $this->generateSign($signParams);

        // 调试日志
        error_log("原始签名: " . $sign);
        error_log("本地签名: " . $localSign);
        error_log("签名参数: " . json_encode($signParams));

        if ($sign === $localSign) {
            // 验证支付状态 - 易支付可能有不同的状态字段
            $tradeStatus = $postData['trade_status'] ?? $postData['status'] ?? '';
            if (in_array($tradeStatus, ['TRADE_SUCCESS', 'success', 'SUCCESS'])) {
                return $postData;
            }
        }

        return false;
    }

    /**
     * 处理支付回调
     */
    public function handleNotify($postData) {
        $verifiedData = $this->verifyNotify($postData);
        
        if ($verifiedData) {
            $orderNo = $verifiedData['out_trade_no'];
            $paymentNo = $verifiedData['trade_no'];
            $amount = $verifiedData['money'];
            
            // 更新订单状态
            $orderManager = new OrderManager();
            $order = $orderManager->getOrderByNo($orderNo);
            
            if ($order && $order['status'] == 'pending') {
                // 检查金额是否匹配
                if (abs($order['total_amount'] - $amount) < 0.01) {
                    // 更新订单状态为已完成
                    $orderManager->updateOrderStatus($order['id'], 'completed', $paymentNo);
                    
                    // 分配CDK码
                    $this->assignCDKToOrder($order['id'], $order['product_id']);
                    
                    $this->logPaymentSuccess($orderNo, $paymentNo, $amount);
                    return true;
                }
            }
        }
        
        $this->logPaymentFailure($postData['out_trade_no'] ?? '', '验证失败');
        return false;
    }

    /**
     * 分配CDK码给订单
     */
    private function assignCDKToOrder($orderId, $productId) {
        $cdkManager = new CDKManager();
        $productManager = new ProductManager();
        $orderManager = new OrderManager();
        
        // 获取可用的CDK码
        $availableCDK = $cdkManager->getAvailableCDK($productId);
        
        if ($availableCDK) {
            // 使用CDK码
            $cdkManager->useCDK($availableCDK['id'], $orderId);
            
            // 更新订单的CDK码字段
            $orderManager->updateOrderCDK($orderId, $availableCDK['cdk_code']);
            
            // 减少商品库存
            $productManager->decreaseStock($productId);
            
            $this->logCDKAssignment($orderId, $availableCDK['cdk_code']);
            return $availableCDK['cdk_code'];
        }
        
        return false;
    }

    /**
     * 查询支付状态
     */
    public function queryPayment($orderNo) {
        $params = [
            'pid' => $this->config['pid'],
            'out_trade_no' => $orderNo
        ];
        
        $params['sign'] = $this->generateSign($params);
        $params['sign_type'] = 'MD5';
        
        $queryUrl = $this->config['api_url'] . '?' . http_build_query($params);
        
        // 发送查询请求
        $response = $this->httpRequest($queryUrl);
        
        if ($response) {
            $result = json_decode($response, true);
            if ($result && $result['code'] == 1) {
                return $result['data'];
            }
        }
        
        return false;
    }

    /**
     * HTTP请求
     */
    private function httpRequest($url, $data = null, $method = 'GET') {
        $ch = curl_init();
        
        if ($method == 'POST' && $data) {
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        } elseif ($method == 'GET' && $data) {
            $url .= '?' . http_build_query($data);
        }
        
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        
        if ($httpCode == 200) {
            return $response;
        }
        
        return false;
    }

    /**
     * 记录支付请求
     */
    private function logPaymentRequest($orderNo, $params) {
        $sql = "INSERT INTO payment_logs (order_no, action, params, created_at) VALUES (?, 'request', ?, NOW())";
        $this->db->query($sql, [$orderNo, json_encode($params)]);
    }

    /**
     * 记录支付成功
     */
    private function logPaymentSuccess($orderNo, $paymentNo, $amount) {
        $sql = "INSERT INTO payment_logs (order_no, payment_no, action, amount, created_at) VALUES (?, ?, 'success', ?, NOW())";
        $this->db->query($sql, [$orderNo, $paymentNo, $amount]);
    }

    /**
     * 记录支付失败
     */
    private function logPaymentFailure($orderNo, $reason) {
        $sql = "INSERT INTO payment_logs (order_no, action, params, created_at) VALUES (?, 'failure', ?, NOW())";
        $this->db->query($sql, [$orderNo, $reason]);
    }

    /**
     * 记录CDK分配
     */
    private function logCDKAssignment($orderId, $cdkCode) {
        $sql = "INSERT INTO cdk_assign_logs (order_id, cdk_code, assigned_at) VALUES (?, ?, NOW())";
        $this->db->query($sql, [$orderId, $cdkCode]);
    }

    /**
     * 获取支持的支付方式
     */
    public function getSupportedPayments() {
        return [
            'alipay' => '支付宝',
            'wxpay' => '微信支付',
            'qqpay' => 'QQ支付',
            'bank' => '网银支付'
        ];
    }

    /**
     * 获取支付统计
     */
    public function getPaymentStatistics($days = 7) {
        $sql = "SELECT 
                COUNT(*) as total_payments,
                SUM(CASE WHEN action = 'success' THEN 1 ELSE 0 END) as success_payments,
                SUM(CASE WHEN action = 'failure' THEN 1 ELSE 0 END) as failed_payments,
                SUM(CASE WHEN action = 'success' THEN amount ELSE 0 END) as total_amount
                FROM payment_logs 
                WHERE created_at >= DATE_SUB(NOW(), INTERVAL ? DAY)";
        
        $result = $this->db->query($sql, [$days]);
        $stats = !empty($result) ? $result[0] : [
            'total_payments' => 0,
            'success_payments' => 0,
            'failed_payments' => 0,
            'total_amount' => 0
        ];
        
        // 计算成功率
        $stats['success_rate'] = $stats['total_payments'] > 0 ? 
            round(($stats['success_payments'] / $stats['total_payments']) * 100, 2) : 0;
        
        return $stats;
    }
}
